//
//  160_相交链表.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/3/8.
/**
 https://leetcode.cn/problems/intersection-of-two-linked-lists/description/
 两个链表相交的点
 */

import UIKit

class XiangJiaoList: NSObject {
    
    func QA() {
        var link1 =  LinkedList<Int>()
        var link =  LinkedList<Int>()

        let head = link.creatList(array: [1,3, 5,7, 9, 3, 4])
        let head1 = link1.creatList(array: [1,2,6, 3,4])
        
        LinkedList.printList(head)
        LinkedList.printList(head1)

        let newHead = getIntersectionNode(head, head1)
        LinkedList.printList(newHead)
    }
    
    /// 精简写法
    func getIntersectionNode(_ headA: ListNode<Int>?, _ headB: ListNode<Int>?) -> ListNode<Int>? {
        if headA == nil || headB == nil {
            return nil
        }
        var currentA = headA
        var currentB = headB
        while currentA !== currentB {
            currentA = currentA != nil ? currentA?.next : headB
            currentB = currentB != nil ? currentB?.next : headA
        }
        return currentA
    }
    
    
    
}
